<script setup lang="ts" name="RoleEdit">
import { DATA_SCOPE_COLUMN, DATA_SCOPE_ENUM } from "@/views/system/role/const";
import { SYS_NORMAL_DISABLE_ENUM } from "@/global/const";
import { dataScopeApi, deptTreeSelectApi, getRoleApi } from "@/api/system/role";

const { proxy } = getCurrentInstance();

const emit = defineEmits(['closeDialog']);

const props = defineProps({
  id: {
    default: null,
  },
  title: {
    type: String,
    default: false,
  }
})

// 角色管理表单
const roleFormRef = ref(null);

// 部门树组件
const deptRef = ref(null);

// 部门树列表
const deptList = ref<OptionRecord[]>([])

// 部门树节点列表
const deptNodeList = ref<OptionRecord[]>([])

// 弹窗开关
const open = ref(false);

// 表单数据
const form = ref<RoleRecord>({});

// 展开/折叠
const deptExpand = ref(false);

// 全选/全不选
const deptNodeAll = ref(false);

// 表单校验
const rules = ref({});

// 加载
const loading = ref(false);

/** 获取角色管理详情 */
async function getData() {
  reset();
  if (isEmpty(props.id)) {
    open.value = true;
  } else {
    try {
      const response = await getRoleApi(props.id);
      form.value = response.data;
      open.value = true;
    } catch (err) {
      console.error(err)
      closeDialog(false);
    }
  }
  getTreeDept();
}


/** 根据角色ID查询部门树结构 */
async function getTreeDept() {
  const { checkedKeys, depts } = await deptTreeSelectApi(props.id);

  deptList.value = depts;
  deptRef.value.setCheckedKeys(checkedKeys);
  deptNodeList.value = getAllDeptNode(deptList.value);
}

function getAllDeptNode(deptTreeList: OptionRecord[], nodeList: OptionRecord[] = []) {
  deptTreeList.forEach(item => {
    nodeList.push(item)
    if (item.children && item.children.length) {
      getAllDeptNode(item.children, nodeList)
    }
  })
  return nodeList;

}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value) {
  const treeList = deptList.value;
  treeList.forEach(item => {
    deptRef.value.store.nodesMap[item.id].expanded = value;
  })
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value) {
  deptRef.value.setCheckedNodes(value ? deptNodeList.value : []);
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value) {
  form.value.deptCheckStrictly = value;
}

/** 表单重置 */
function reset() {
  form.value = {
    roleId: null,
    roleName: null,
    roleKey: null,
    dataScope: null,
    deptIds: [],
    roleSort: null,
    menuIds: [],
    permissions: [],
    status: SYS_NORMAL_DISABLE_ENUM.normal,
    deptCheckStrictly: null,
    remark: null,
  };
}

/** 关闭弹窗 */
function closeDialog(refresh: boolean) {
  open.value = false;
  emit("closeDialog", refresh);
}

/** 提交按钮 */
function submitForm() {
  roleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (form.value.dataScope == DATA_SCOPE_ENUM.customDataScope) {
        form.value.deptIds = getMenuAllCheckedKeys();
      }else {
        form.value.deptIds = [];
      }
      dataScopeApi(form.value).then(() => {
        // @ts-ignore
        proxy.$modal.msgSuccess("修改成功");
        loading.value = false;
        closeDialog(true);
      }).catch(() => {
        loading.value = false
      });

    }
  })
}

/** 所有部门节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的部门节点
  const checkedKeys = deptRef.value.getCheckedKeys();

  // 半选中的部门节点
  const halfCheckedKeys = deptRef.value.getHalfCheckedKeys();

  checkedKeys.unshift(...halfCheckedKeys)
  return checkedKeys;
}

watch(open, (val) => {
  if (!val) {
    closeDialog(false);
  }
})

getData();
</script>

<template>
  <!-- 角色管理编辑对话框 -->
  <el-dialog :title="title" v-model="open" width="736px" append-to-body :close-on-click-modal="false">
    <el-form ref="roleFormRef" :model="form" :rules="rules" :inline="true" label-width="98px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" placeholder="请输入角色名称" disabled />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <template #label>
          <span>
            <el-tooltip content="控制器中定义的权限字符，如：admin)" placement="top">
              <icon-svg icon-name="QuestionFilled" />
            </el-tooltip>
            权限字符
          </span>
        </template>
        <el-input v-model="form.roleKey" placeholder="请输入权限字符" disabled />
      </el-form-item>
      <el-form-item label="权限范围" prop="dataScope">
        <el-select v-model="form.dataScope" placeholder="请选择权限范围">
          <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in DATA_SCOPE_COLUMN"
              :key="index"
          />
        </el-select>
      </el-form-item>
      <el-form-item
          label="部门权限"
          prop="menuIds"
          class="item-describe"
          v-if="form.dataScope == DATA_SCOPE_ENUM.customDataScope"
      >
        <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
        <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
        <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect">父子联动</el-checkbox>
        <el-tree
            class="tree-border"
            :data="deptList"
            show-checkbox
            ref="deptRef"
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
        ></el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" v-debounce="submitForm" :loading="loading">确 定</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.tree-border {
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto;
}
</style>